package com.xunker.dictmanager.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.xunker.appointment.model.dictory.DictManager;
import com.xunker.appointment.result.Result;
import com.xunker.appointment.vo.dictManager.DictManagerVo;
import com.xunker.appointment.vo.hospital.ProAndCityVo;
import com.xunker.dictmanager.excel.UploadDataListener;
import com.xunker.dictmanager.service.DictManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("数据字典管理")
@RestController
@RequestMapping("dictory/dictManager")

public class DictManagerController {
    @Autowired
    private DictManagerService dictManagerService;

    /**
     * 查询所有
     *
     * @return
     */
    @ApiOperation(value = "根据id查询子节点")
    @GetMapping("findChildData/{id}")
    public Result findDMChildDataById(@PathVariable Long id) {
        List<DictManager> list = dictManagerService.findChildData(id);
        return Result.ok(list);
    }

    /**
     * 导出excel模板
     *
     * @return
     */
    @ApiOperation("导出模板")
    @GetMapping("exportExcelModel")
    public void exportExcelModel(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DictManager.class).sheet("数据字典").doWrite(null);
    }

    /**
     * 将Excel数据导入到数据库中
     *
     * @return
     */
    @ApiOperation("导入数据")
    @PostMapping("importExcelData/{parentId}")
    @CacheEvict(value = "dict", allEntries = true)//将<findChild,dict>键值对中缓存数据清除
    public Result importExcelData(MultipartFile file, @PathVariable Long parentId) throws IOException {
        EasyExcel.read(file.getInputStream(), DictManager.class, new UploadDataListener(parentId, dictManagerService)).sheet().doRead();
        return Result.ok();
    }

    @GetMapping("exportExcelData")
    public void exportExcelData(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典数据", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            List<DictManager> list = dictManagerService.list();
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), DictManagerVo.class).autoCloseStream(Boolean.TRUE).sheet("数据字典")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * nacos服务中心
     */
    //根据dictory_code和value查询name
    @GetMapping("getName/{dictoryCode}/{value}")
    public String getNameByCN(@PathVariable String dictoryCode,@PathVariable String value){
        String dictName=dictManagerService.getName(dictoryCode,value);
        return dictName;
    }
    //根据value查询name
    @GetMapping("getName/{value}")
    public String getNameByCN(@PathVariable String value){
        String dictName=dictManagerService.getName(value);
        return dictName;
    }
    //根据dictory_code和value查询省和城市
    @GetMapping("getProAndCity/{dictoryCode}/{value}")
    public ArrayList<ProAndCityVo> getProAndCityByCN(@PathVariable String dictoryCode, @PathVariable String value){
        ArrayList<ProAndCityVo> proAndCity=dictManagerService.ProAndCity(dictoryCode,value);
        return proAndCity;
    }
}
